package main;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;

public class ServerListenerThread extends Thread {
  private ServerSocket serverListeningSocket;
  private final int listeningPort;
  private final ArrayBlockingQueue<Socket> socketsQueue;
  
  ServerListenerThread(int listeningPort, ArrayBlockingQueue<Socket> socketQueue) {
    this.listeningPort = listeningPort;
    socketsQueue = socketQueue;
  }
  
  @Override public void run() {
    // start handler thread that handles requests from clients
    ServerHandlerThread serverHandler = new ServerHandlerThread(socketsQueue);
    serverHandler.start();
    // listen
    Socket socket = null;
    try {
      serverListeningSocket = new ServerSocket(listeningPort);
      while (true)
        try {
          // get the socket from client
          socket = serverListeningSocket.accept();
          // put the socket in the waiting queue
          // ignore the socket if there is no place in the queue
          if (!socketsQueue.offer(socket))
            continue; // no place in the queue- drop message
        } catch (IOException e) {
          e.printStackTrace();
        }
    } catch (IOException e) {
      // This happens if we cannot open a socket for listening
      e.printStackTrace();
    } finally {
      try {
        serverListeningSocket.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}
